package gov.gfbzb.advice.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;

/**
 * 线程池
 */
@Configuration
@EnableAsync
public class AsyncConfig {

    @Bean(name = "deepSeekExecutor")
    public Executor deepSeekExecutor() {
        return this.commonExecutor("deepSeekExecutor");
    }

    @Bean("taskExecutor")
    public Executor taskExecutor() {
        return this.commonExecutor("taskExecutor");
    }

    @Bean("jobExecutor")
    public Executor jobExecutor() {
        return this.commonExecutor("jobExecutor");
    }

    /**
     * 返回一个线程池
     * @param prefix 前缀
     * @return 线程池
     */
    public Executor commonExecutor(String prefix) {
        //返回可用处理器的Java虚拟机的数量 12
        int i = Runtime.getRuntime().availableProcessors();
        System.out.println("系统最大线程数  ： " + i);
        // 至少保留4个核心线程
        int corePoolSize = Math.max(4, i);
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 核心线程池大小
        executor.setCorePoolSize(corePoolSize);
        // 最大线程数为 core 的两倍
        executor.setMaxPoolSize(corePoolSize * 2);
        //配置队列容量，最多排队200个任务
        executor.setQueueCapacity(200);
        //活跃时间
        executor.setKeepAliveSeconds(30);
        //线程名字前缀
        executor.setThreadNamePrefix(prefix+" -");
        //设置此执行程序应该在关闭时阻止的最大秒数，以便在容器的其余部分继续关闭之前等待剩余的任务完成他们的执行
        executor.setAwaitTerminationSeconds(60);
        //等待所有的任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        return executor;
    }
}
